<template>
  <div class="userPage">
    <el-container>
      <splitpanel title="组织架构" icon="company" :request="request" :department="department" :defaultProps="defaultProps"
                  @handleNodeClick="handleNodeClick"></splitpanel>
      <el-main class="el-mainBox">
        <div class="rightLayout">
          <formbox :SysEmployeeForm="SysEmployeeForm"
                   @querySysEmployee="querySysEmployee"
                   @editClick="editClick"
                   @deleteSysEmployee="deleteSysEmployee"
                   @resetSysEmployee="resetSysEmployee"
                   @resetPwd="resetPwd"
                   @authorClick="openPermissionSetting"
                   @openSysEmployee="openSysEmployee"

          >
            <!--            @loadSysUser="loadSysUser"-->
          </formbox>
          <div style="height: 50px;padding-left: 10px;border-top: 1px solid #eeeeee">
            <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize"
                        @pagination="loadsysEmployee"></pagination>
          </div>
        </div>
      </el-main>
      <!--  授权    -->
      <el-dialog title="用户授权" :visible.sync="dialogFormVisible" :time="times">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="角色权限" name="first">
            <el-table
              ref="multipleTable"
              :data="roleData"
              tooltip-effect="dark"
              style="width: 100%"
              border
              height="300px"
              @selection-change="formClick"
            >
              <el-table-column
                type="selection"
                width="55"
                align="center"
              >
              </el-table-column>
              <el-table-column
                prop="name"
                label="角色名字"
                width="200"
                align="center"
              >
              </el-table-column>
              <el-table-column
                prop="remark"
                label="角色说明"
                show-overflow-tooltip>
              </el-table-column>
            </el-table>
          </el-tab-pane>
                    <el-tab-pane label="部门权限" name="second">
                      <div style="padding: 20px;border: 1px solid #DCDFE6;border-radius: 3px;height: 300px;overflow: auto">
                        <el-tree highlight-current :data="shops" show-checkbox  :default-expand-all="show_header"
                                 :props="defaultProps" node-key="id" ref="tree"
                                 @check-change="treeClick">
                      <span class="slot-t-node" slot-scope="{ node, data }">
                          <i :class="{'el-icon-office-building primary': data.type==0, 'el-icon-school':data.type==1}"/>
                          <span>{{ data.name }}</span>
                      </span>
                        </el-tree>
                      </div>
                    </el-tab-pane>
<!--          <el-tab-pane label="部门权限" name="third">-->
<!--            <el-table-->
<!--              ref="shopTable"-->
<!--              :data="shops"-->
<!--              tooltip-effect="dark"-->
<!--              style="width: 100%"-->
<!--              border-->
<!--              height="300px"-->
<!--              @selection-change="shopClick"-->
<!--            >-->
<!--              <el-table-column-->
<!--                type="selection"-->
<!--                width="55"-->
<!--                align="center"-->
<!--              >-->
<!--              </el-table-column>-->
<!--              <el-table-column-->
<!--                prop="name"-->
<!--                label="部门名称"-->
<!--              >-->
<!--              </el-table-column>-->
<!--            </el-table>-->
<!--          </el-tab-pane>-->
        </el-tabs>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" :loading="editClicked" @click="updateSysUser">确 定</el-button>
        </div>
      </el-dialog>
    </el-container>
  </div>
</template>

<style>
.userPage {
  min-height: calc(100vh - 84px);
  display: flex;
  flex-direction: row;
}

.leftLayout {
  display: flex;
  flex-direction: row;
}

.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 200px;
  min-height: 400px;
}

.rightLayout {
  width: 100%;
  height: 100%;
}

.el-aside {
  color: #333;
}

.user-order {
  padding: 20px 20px 10px 20px;
  box-sizing: border-box;
}

.el-menu {
  border: none !important;
}

.el-mainBox {
  padding: 0 !important;
}

.el-footerBox {
  height: 50px !important;
  line-height: 50px !important;
}
</style>

<script>
import permission from '@/directive/permission/index.js' // 权限判断指令
import formbox from './components/formbox'
import splitpanel from '@/components/SplitPanel'
import Pagination from '@/components/Pagination';
import {mapGetters} from 'vuex'
import {list, del, update} from '@/api/sysEmployee'
import {list as officeList, list as treeList} from '@/api/sysOffice'
import {EventBus} from '@/api/eventBus'
import utils from '../../utils/utils.js'
import {list as sysUserList, find,update as updateUserList, resetPwd, updateScopes} from "@/api/sysUser";
import {list as roleList} from "@/api/sysRole";

export default {
  name: 'sysEmployee-list',
  directives: {permission},
  data() {
    return {
      isCollapse: false,
      queryName: '',
      queryNumber: '',
      keyword: {
        name: '',
        number: ''
      },
      pageNum: 1,// 当前页
      pageSize: 20, // 每页显示条目个数
      total: 0,// 总条目数
      SysEmployeeForm: [],
      officeId: '',
      department: [],
      officeData: [],
      defaultProps: {
        children: 'childrens',
        label: 'name'
      },
      sysEmployeeOpenForm: {
        id: '',
        status: ''
      },
      sysUserForm: [],
      request: 'sysOffice',
      roleData: [],
      roles: [],
      shops: [],
      offices: [],
      shopData: [],
      show_header: true,
      userId: '',
      times: '',
      dialogFormVisible: false,
      activeName: 'first',
      editClicked: false
    };
  },
  components: {
    formbox, splitpanel, Pagination
  },
  computed: {
    ...mapGetters([
      'sidebar',
    ]),
  },
  created() {
    var _this = this
    this.loadSysUser()
    this.loadsysEmployee()
    this.treeList()
    this.loadShop()
    EventBus.$on('sysEmployee-add', res => { // 监听新增完毕
      // 更新列表数组
      _this.SysEmployeeForm.splice(0, 0, res)
    })
    EventBus.$on('sysEmployee-edit', res => { // 监听新增完毕
      // 更新列表数组
      for (var i = 0; i < _this.SysEmployeeForm.length; i++) {
        if (_this.SysEmployeeForm[i].id == res.id) {
          _this.SysEmployeeForm[i] = res
        }
      }
    })
  },
  methods: {
    querySysEmployee(data) {
      var _this = this
      _this.keyword.name = data.name;
      _this.keyword.number = data.number;
      _this.pageNum = 1;
      _this.loadSysUser()
      _this.loadsysEmployee()
    },
    resetSysEmployee() {
      this.keyword.name = '';
      this.keyword.number = '';
      this.pageNum = 1;
      this.loadsysEmployee()
    },
    editClick(data) {
      console.log(data);
      this.$router.push({
        path: '/sysEmployee/edit',
        query: {id: data.id}
      });
    },
    leftBotton: function () {
      this.isCollapse = !this.isCollapse
    },
    handleNodeClick(data) {
      console.log(data);
      var _this = this
      _this.pageNum = 1;
      _this.pageSize = 10;
      _this.total = 0;
      _this.officeId = data.id;
      _this.loadsysEmployee()
    },
    loadsysEmployee() {
      var _this = this
      _this.sysUserForm = []
      _this.loadSysUser()
      let params = new URLSearchParams();
      params.append('pageNum', _this.pageNum);
      params.append('pageSize', _this.pageSize);
      params.append('empNo', _this.keyword.number);
      params.append('name', _this.keyword.name);
      params.append('officeId', _this.officeId);
      list(params).then(response => {
        // console.log(response)
          response.data.data.map(item => {
            item.loading = false
            item.pwdLoading = false
            if (item.userId) {
              for (let i in this.sysUserForm) {
                if (_this.sysUserForm[i].id == item.userId) {
                  item.roleName = _this.sysUserForm[i].roleName
                  item.username = _this.sysUserForm[i].username
                  if (utils.isNull(_this.sysUserForm[i].wxId)) {
                    item.wxId = _this.sysUserForm[i].wxId
                  } else item.wxId = ''
                  // console.log(item)
                }
              }
            }
            return item
          })
        _this.SysEmployeeForm = response.data.data
        _this.total = response.data.total
      }).catch(error => {
        console.log('error!!')
      });
    },
    loadSysUser() {
      var _this = this
      let params = new URLSearchParams();
      sysUserList(params).then(response => {
        // console.log(response, 'loadSysUser')
        response.data.data.map(item => {
          item.loading = false
          item.pwdLoading = false
          return item
        })
        _this.sysUserForm = response.data.data
      }).catch(error => {
        console.log('error!!')
      });
    },
    deleteSysEmployee(data) {
      console.log(data);
      var _this = this;
      this.$confirm("是否确定需要删除", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: 'warning'
      }).then(() => {
        del(data).then(response => {
          console.log(response)
          _this.SysEmployeeForm.forEach(function (item, index) {
            if (item.id == data) {
              _this.SysEmployeeForm.splice(index, 1)
            }
          });
          _this.$message({
            message: response.content,
            offset: 120,
            center: true
          });
        }).catch(error => {
          console.log('error!!')
        });
      })
    },
    treeList() {
      var _this = this
      treeList().then(response => {
        console.log(response)
        _this.department = response.data
      })
    },
    openSysEmployee(row) {
      var _this = this
      console.log(row);
      this.sysEmployeeOpenForm.id = row.id;
      if (row.status == 0) {
        this.sysEmployeeOpenForm.status = 1
      } else if (row.status == 1) {
        this.sysEmployeeOpenForm.status = 0
      }

      update(_this.sysEmployeeOpenForm).then(response => {
        _this.SysEmployeeForm.forEach(function (item) {
          if (item.id == row.id) {
            item.status = response.data.status
          }
        })
          this.sysEmployeeOpenForm.id = row.userId;
        updateUserList(_this.sysEmployeeOpenForm).then(response => {
          _this.sysUserForm.forEach(function (item) {
          if (item.id == row.userId) {
            item.status = response.data.status
          }
          })
        })
        _this.$message({
          message: response.content,
          offset: 120,
          center: true
        });
        row.loading = false
      }).catch(error => {
        row.loading = false
      });
    },

    resetPwd(row) {
      var _this = this
      row.pwdLoading = true
      let data = {
        userId: row.userId
      }
      resetPwd(data).then(response => {
        console.log(response)
        _this.$message({
          message: response.content,
          offset: 120,
          center: true
        });
        row.pwdLoading = false
      }).catch(error => {
        row.pwdLoading = false
        console.log('error!!')
      });
    },
    roleList: function () {
      let _this = this
      let params = new URLSearchParams();
      roleList(params).then(response => {
        _this.roleData = response.data.data
      })
    },
    updateSysUser() {
      var _this = this
      this.editClicked = true
      var officeList = []
      var shopList = []
      _this.offices.forEach(function (item) {
        var item1 = {
          scopeType: 1,
          officeId: item
        }
        officeList.push(item1)
      });
      _this.shopData.forEach(item => {
        var item1 = {
          scopeType: 2,
          officeId: item
        }
        officeList.push(item1)
      })
      let params = new URLSearchParams();
      _this.roles.forEach(function (item) {
        params.append('roles', item);
      });
      params.append('userId', _this.userId)
      updateScopes(params, officeList).then(response => {
        _this.dialogFormVisible = false
        _this.loadSysUser()
        _this.loadsysEmployee()
        _this.$message({
          message: response.content,
          offset: 120,
          center: true
        });
        _this.editClicked = false
      }).catch(error => {
        _this.editClicked = false
      });
    },

    //permission Setting
    openPermissionSetting(row) {
      var _this = this
      console.log(row);
      this.roleList();
      this.userId = row.userId;
      console.log('userId', this.userId)
      this.dialogFormVisible = true
      this.times = new Date().getSeconds()
      setTimeout(function () {
        _this.findSysUser()
      }, 1000)
    },
    findSysUser() {
      this.shops.forEach((item, index) => {
        console.log(this.$refs.shopTable.data[index],'shopTable')
        this.$refs.shopTable.toggleRowSelection(this.$refs.shopTable.data[index], false)
      })
      find(this.userId).then(response => {
        var officeList = []
        var shopList = []
        response.data.dataScopeList.forEach(item => {
          if (item.scopeType == 1) {
            var off = {
              id: item.officeId
            }
            officeList.push(off)
          } else {
            shopList.push(item)
          }
        })

        this.shops.forEach((item, index) => {
          shopList.forEach(findItem => {
            if (item.id == findItem.officeId) {
              this.shopData.push(findItem.officeId)
              this.$refs.shopTable.toggleRowSelection(this.$refs.shopTable.data[index], true)
            }
          })
        })
        this.roleData.forEach((item, index) => {
          response.data.roleList.forEach(findItem => {
            if (item.id == findItem.id) {
              this.roles.push(item.id);
              this.$refs.multipleTable.toggleRowSelection(this.$refs.multipleTable.data[index], true)
            }
          })
        })
      })
    },
    formClick(val) {
      var _this = this
      _this.roles = [];
      val.forEach(function (item) {
        _this.roles.push(item.id)
      })
    },
    loadShop() {
      let params = {
        pageSize: 10000,
      }
      officeList(params).then(res => {
        this.shops = res.data
        console.log('loadShop', this.shops)
      })
    },
    shopClick(val) {
      var _this = this
      _this.shopData = [];
      val.forEach(function (item) {
        _this.shopData.push(item.id)
      })
    },
    handleClick(tab, event) {
      // console.log(tab, event);
    },
    treeClick(data, type) {
      var _this = this
      if (type == true && data.childrens == '') {
        _this.offices.push(data.id)
      } else if (type == false && data.childrens == '') {
        console.log(data)
        _this.offices.forEach(function (item, index) {
          if (item == data.id) {
            _this.offices.splice(index, 1)
          }
        })
      }
    },
  }
}
</script>
